package com.example.vv.model.login.base.presenter;

import android.util.Log;

import com.example.vv.fragmentWork.entity.LoginEntity;
import com.example.vv.fragmentWork.mvp.MvpPresenter;
import com.example.vv.fragmentWork.mvp.ViewISNullException;
import com.example.vv.model.login.base.contract.LoginContract;
import com.example.vv.model.login.base.model.LoginModel;
import com.example.vv.req.REQ_LOGIN;
import com.example.vv.res.net.BaseResponse;
import com.google.gson.Gson;

import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

public class LoginPresenter extends MvpPresenter<LoginContract.View,LoginContract.Model> implements LoginContract.Presenter {
    @Override
    public void attach(LoginContract.View view) {
        super.attach(view);
        model = new LoginModel();
    }

    @Override
    public void login() {
        try {
            REQ_LOGIN re = new REQ_LOGIN(view().getUserName(),view().getPassWord());
            model.login(re)
                    .map(new Function<BaseResponse, LoginEntity>() {
                        @Override
                        public LoginEntity apply(BaseResponse baseResponse) throws Exception {
                            view().getMsg(baseResponse.getErrorMsg());
                            LoginEntity loginEntities = new Gson().fromJson(baseResponse.getData(),LoginEntity.class);

                            return loginEntities;
                        }
                    })
                    .subscribe(new Consumer<LoginEntity>() {
                        @Override
                        public void accept(LoginEntity loginEntity)  {
                            try {
                                view().setLoginEntity(loginEntity);
                            } catch (ViewISNullException e) {
                                Log.d("sdf", e.getMessage());
                                e.printStackTrace();
                            }
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            throwable.printStackTrace();
                        }
                    });

        } catch (ViewISNullException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean isFormat() {
        return true;
    }
}
